package com.acc.mobileappr.util;

import com.acc.mobileappr.constant.AppConstant;
import com.acc.mobileappr.constant.BBPushConstant;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;

/**
 * Utility class for sending BB Push message via BES
 *
 * @author abiel@ICN
 */
public class PushUtil {

    private final String mdsHost = AppConstant.getProperty(AppConstant.PROP_MDS_HOST);
    private final int mdsPort = AppConstant.getIntegerProperty(AppConstant.PROP_MDS_PORT);
    private final String devicePort = AppConstant.getProperty(AppConstant.PROP_DEVICE_PORT);
    private final String gatewayIp = AppConstant.getProperty(AppConstant.PROP_APPLICATION_IP);
    private final String gatewayPath = AppConstant.getProperty(AppConstant.PROP_APPLICATION_PATH);
    private final String gatewayPort = AppConstant.getProperty(AppConstant.PROP_APPLICATION_PORT);
    //static final Logger logger = Logger.getLogger(PushUtil.class);

    /**
     * Constructor
     */
    public PushUtil(){
        //BasicConfigurator.configure();
    }

    /**
     * Method for sending Data thru Push service
     *
     * @param devicePin  BB device Pin
     * @param data       Data to be sent
     * @return           Sent status
     */
    public String pushData(String devicePin, String pushId, String data) {

        try {

            int delay = AppConstant.getIntegerProperty("app.pushdelay");
            Thread.sleep(delay);

        } catch (Exception e) {

            e.printStackTrace();

        }

        String pushStatus = "";
        int responseCode=200;
        HttpURLConnection conn, conn2;

        try {
            URL url2 = new URL("http://" + mdsHost + ":" + mdsPort);
            Util.print("URL to push is: http://" + mdsHost + ":" + mdsPort);

            conn2 = (HttpURLConnection) url2.openConnection();
            conn2.setRequestMethod(BBPushConstant.HEADER_GET);
            conn2.setRequestProperty(BBPushConstant.HEADER_USER_AGENT, "BlackBerry9000/4.6.0.92");
            conn2.setRequestProperty(BBPushConstant.HEADER_UA_PROF, "http://www.blackberry.net/go/mobile/profiles/uaprof/9000/4.6.0.92.rdf");
            conn2.setRequestProperty("Rim-device-id", devicePin);

            Util.print(conn2.getRequestMethod());
            Util.print(conn2.getRequestProperty(BBPushConstant.HEADER_USER_AGENT));
            Util.print(conn2.getRequestProperty(BBPushConstant.HEADER_UA_PROF));
            Util.print(conn2.getRequestProperty("Rim-device-id"));

            responseCode= conn2.getResponseCode();
            Util.print("status: " + responseCode + ": "+AppConstant.getProperty("message.push."+responseCode) );
            conn2.disconnect();

            responseCode=0;
            pushId = pushId+"-"+(new Date()).getTime();
            
            URL url = new URL("http", mdsHost, mdsPort, "/push?DESTINATION=" + devicePin + "&PORT=" + devicePort + "&REQUESTURI=" + mdsHost);
            System.out.println(" sending RIM request to " + url.toString() + "; pushId = " + pushId);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true); //For receiving the confirmation
            conn.setDoOutput(true); //For sending the data
            conn.setRequestMethod(BBPushConstant.HEADER_POST); //Post the data to the proxy
            conn.setRequestProperty(BBPushConstant.HEADER_PUSH_ID, pushId);
            conn.setRequestProperty(BBPushConstant.HEADER_PUSH_NOTIFY_URL, "http://" + gatewayIp + ":" + gatewayPort + gatewayPath);
            conn.setRequestProperty(BBPushConstant.HEADER_PUSH_RELIABILITY_MODE, "TRANSPORT");  //"TRANSPORT" "APPLICATION"

            Util.print("Request-method:"+conn.getRequestMethod());
            Util.print(BBPushConstant.HEADER_PUSH_ID +":"+conn.getRequestProperty(BBPushConstant.HEADER_PUSH_ID));
            Util.print(BBPushConstant.HEADER_PUSH_NOTIFY_URL +":"+conn.getRequestProperty(BBPushConstant.HEADER_PUSH_NOTIFY_URL));
            Util.print(BBPushConstant.HEADER_PUSH_RELIABILITY_MODE +":"+conn.getRequestProperty(BBPushConstant.HEADER_PUSH_RELIABILITY_MODE));

            Util.print(data.getBytes().toString());

            //Write the data
            OutputStream out = conn.getOutputStream();
            out.write(data.getBytes());
            out.close();

            InputStream ins = conn.getInputStream();

            int contentLength = conn.getContentLength();
            if (contentLength > 0) {
                byte[] someArray = new byte[contentLength];
                DataInputStream dins = new DataInputStream(ins);
                dins.readFully(someArray);
                Util.print(new String(someArray));
            }
            ins.close();
            conn.disconnect();
            pushStatus = "OK~" + pushId;

        } catch (IOException e) {

            e.printStackTrace();
            pushStatus="ERROR~"+ e.getMessage()+"\r\nPlease check MDAT log on BES Server";
            Util.error(pushStatus);

        }catch(Exception e){
            e.printStackTrace();
            Util.error(e.getMessage());
        }

        return pushStatus;

    }

}
